// 提供复用逻辑的函数

import { useIntersectionObserver } from '@vueuse/core'
import { onUnmounted, ref } from 'vue'
import { useIntervalFn } from '@vueuse/shared'
import dayjs from 'dayjs'

export const useLazyData = (apiFn) => {
  const result = ref([])
  const target = ref(null)
  // stop 停止观察
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      // isIntersecting 是否进入可视区
      // console.log('进入可视区')
      if (isIntersecting) {
        stop()
        // 调用api获取数据
        apiFn().then(data => {
          result.value = data.result
        })
      }
    },
    // 配置选项，相交的比例大于0就触发
    {
      threshold: 0
    }
  )
  return { result, target }
}

export const usePayTime = () => {
  // 倒计时逻辑 后端提供 countdown 倒计时秒数
  const time = ref(0)
  const timeText = ref('')
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    if (time.value <= 0) pause()
  }, 1000, false)

  onUnmounted(() => {
    pause()
  })

  // 开启定时器
  const start = (countDown) => {
    time.value = countDown
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    resume()
  }
  return { start, timeText }
}
